import { HttpContext } from '@angular/common/http';
import { ChangeDetectionStrategy, Component, inject, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { StartupService } from '@core';
import { ReuseTabService } from '@delon/abc/reuse-tab';
import { ALLOW_ANONYMOUS, DA_SERVICE_TOKEN, JWTTokenModel } from '@delon/auth';
import { _HttpClient } from '@delon/theme';
import { encryptByRSA } from '@shared';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzSpinComponent } from 'ng-zorro-antd/spin';
import { Api } from 'src/app/shared/api/api';
import { ResponseCode } from 'src/app/shared/response.code';

@Component({
  selector: 'app-login-callback',
  templateUrl: `callback.component.html`,
  changeDetection: ChangeDetectionStrategy.Default,
  imports: [NzSpinComponent]
})
export class CallbackComponent implements OnInit {
  code = '';
  state = '';
  target = '';
  publicKey = '';

  protected readonly http = inject(_HttpClient);
  private readonly msg = inject(NzMessageService);

  private readonly route = inject(Router);
  private readonly startupSrv = inject(StartupService);

  private readonly router = inject(ActivatedRoute);
  private readonly reuseTabService = inject(ReuseTabService, { optional: true });
  private readonly tokenService = inject(DA_SERVICE_TOKEN);

  constructor() {
    this.router.queryParams.subscribe(res => {
      if (!res) {
        this.msg.error('参数有误');
        return;
      }
      this.code = res['code'];
      this.state = res['state'];
      this.target = res['target'];
    });
  }

  ngOnInit(): void {
    if (this.code) {
      this.getPublicKey();
    }
  }

  getPublicKey() {
    this.http
      .get(Api.PublicKeyApi, null, {
        context: new HttpContext().set(ALLOW_ANONYMOUS, true)
      })
      .subscribe((res: NzSafeAny) => {
        if (res && res.code === ResponseCode.SUCCESS) {
          this.publicKey = res.data;
          this.loginByWeixin();
        }
      });
  }

  loginByWeixin() {
    let data = new FormData();
    data.append('code', encryptByRSA(this.publicKey, this.code) as string);
    data.append('thirdType', encryptByRSA(this.publicKey, '0') as string);
    data.append('scope', 'user');
    this.http
      .post(
        Api.ThirdQrLoginApi,
        data,
        {},
        {
          context: new HttpContext().set(ALLOW_ANONYMOUS, true)
        }
      )
      .subscribe({
        next: (res: NzSafeAny) => {
          if (!res.data) {
            this.msg.error(res.message || '登录失败');
            this.route.navigateByUrl('/passport/login');
            return;
          }
          if (this.target) {
            this.goTarget();
          } else {
            // 清空路由复用信息
            this.reuseTabService?.clear();
            // 设置用户Token信息
            const user = { token: res.data };
            this.tokenService.set(user);
            // 重新获取 StartupService 内容，我们始终认为应用信息一般都会受当前用户授权范围而影响
            this.startupSrv.load().subscribe(() => {
              let url = this.tokenService.referrer!.url || '/';
              if (url.includes('/passport')) {
                url = '/';
              }
              this.route.navigateByUrl(url);
            });
          }
        },
        error: (error: NzSafeAny) => {
          console.log(error);
          this.msg.error('登录失败，请重新扫码');
          this.route.navigateByUrl('/passport/login?type=2');
        }
      });
  }

  goTarget() {
    let jwtTkoen = this.tokenService.get(JWTTokenModel);
    if (jwtTkoen && jwtTkoen?.token) {
      window.location.href = `${this.target}&token=${jwtTkoen.token}`;
    }
  }
}
